import customtkinter as ctk
import os
import winreg
import ctypes
import subprocess
import webbrowser

ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")

app = ctk.CTk()
app.title("Windows 终极优化器")
app.geometry("600x800")


def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if not is_admin():
    ctk.CTkLabel(app, text="请以管理员权限运行本程序！", text_color="red").pack(pady=20)
    app.mainloop()
    exit()


def set_reg(path, name, value, root=winreg.HKEY_LOCAL_MACHINE):
    try:
        key = winreg.CreateKeyEx(root, path, 0, winreg.KEY_WRITE)
        winreg.SetValueEx(key, name, 0, winreg.REG_DWORD, value)
        winreg.CloseKey(key)
    except Exception as e:
        print(f"注册表设置失败: {e}")


def restore_reg(path, name):
    try:
        key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0, winreg.KEY_WRITE)
        winreg.DeleteValue(key, name)
        winreg.CloseKey(key)
    except Exception as e:
        print(f"恢复注册表失败: {e}")


options = {
    "禁用系统还原": ctk.BooleanVar(value=True),
    "禁用 Windows 更新 & BITS": ctk.BooleanVar(value=True),
    "禁止安装 & 运行程序": ctk.BooleanVar(value=True),
    "卸载 OneDrive": ctk.BooleanVar(value=True),
    "禁用 Cortana": ctk.BooleanVar(value=True),
    "关闭视觉特效": ctk.BooleanVar(value=True),
    "关闭广告 & 应用推荐": ctk.BooleanVar(value=True),
    "关闭后台应用": ctk.BooleanVar(value=True),
    "禁用遥测 & 数据收集": ctk.BooleanVar(value=True),
    "禁用 Windows 错误报告": ctk.BooleanVar(value=True),
    "清理临时文件": ctk.BooleanVar(value=True),
    "禁用 Xbox 相关服务": ctk.BooleanVar(value=True),
}


def disable_restore():
    os.system("wmic /Namespace:\\\\root\\\\default Path SystemRestore Call Disable C:\\\\")
    subprocess.run(["powershell", "-Command", "Disable-ComputerRestore -Drive 'C:'"], shell=True)

def disable_updates():
    os.system("sc stop wuauserv")
    os.system("sc config wuauserv start= disabled")
    os.system("sc stop bits")
    os.system("sc config bits start= disabled")
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "NoAutoUpdate", 1)
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "DisableWindowsUpdateAccess", 1)
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "ExcludeWUDriversInQualityUpdate", 1)
    set_reg(r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\WindowsUpdate", "DoNotConnectToWindowsUpdateInternetLocations", 1)

def block_installs():
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "DisallowRun", 1, winreg.HKEY_CURRENT_USER)
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoRun", 1, winreg.HKEY_CURRENT_USER)
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoAddDevices", 1, winreg.HKEY_CURRENT_USER)
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoInstall", 1, winreg.HKEY_CURRENT_USER)
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoInstallDriveTypeAutoRun", 255, winreg.HKEY_CURRENT_USER)
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\Installer", "DisableMSI", 2)
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\Installer", "NoShellExecute", 1)

def remove_onedrive():
    os.system("taskkill /f /im OneDrive.exe")
    subprocess.run([f"%SystemRoot%\\System32\\OneDriveSetup.exe", "/uninstall"], shell=True)
    one_path = os.path.join(os.environ['USERPROFILE'], "OneDrive")
    if os.path.exists(one_path):
        os.system(f"rd /s /q \"{one_path}\"")
    set_reg(r"HKCU\Software\Microsoft\OneDrive", "Uninstall", 1, winreg.HKEY_CURRENT_USER)
    set_reg(r"HKLM\SOFTWARE\Microsoft\OneDrive", "Uninstall", 1, winreg.HKEY_LOCAL_MACHINE)

def disable_cortana():
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\Windows Search", "AllowCortana", 0)
    set_reg(r"SOFTWARE\Microsoft\Windows\CurrentVersion\Search", "CortanaEnabled", 0, winreg.HKEY_CURRENT_USER)

def visual_effects():
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\Explorer\VisualEffects", "VisualFXSetting", 2, winreg.HKEY_CURRENT_USER)
    subprocess.run(["SystemPropertiesPerformance.exe"], shell=True)

def ads_disable():
    cdm = r"Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager"
    set_reg(cdm, "SystemPaneSuggestionsEnabled", 0, winreg.HKEY_CURRENT_USER)
    set_reg(cdm, "SubscribedContent-338388Enabled", 0, winreg.HKEY_CURRENT_USER)
    set_reg(cdm, "SubscribedContent-310093Enabled", 0, winreg.HKEY_CURRENT_USER)

def disable_bg_apps():
    set_reg(r"Software\Microsoft\Windows\CurrentVersion\BackgroundAccessApplications", "GlobalUserDisabled", 1, winreg.HKEY_CURRENT_USER)

def disable_telemetry():
    set_reg(r"SOFTWARE\Policies\Microsoft\Windows\DataCollection", "AllowTelemetry", 0)
    set_reg(r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\DataCollection", "AllowTelemetry", 0, winreg.HKEY_LOCAL_MACHINE)

def disable_wer():
    os.system("sc stop WerSvc")
    os.system("sc config WerSvc start= disabled")
    set_reg(r"HKLM\Software\Policies\Microsoft\Windows\ErrorReporting", "Disabled", 1)

def clean_temp():
    os.system("del /f /s /q %TEMP%\\*")
    os.system("cleanmgr /sagerun:1")

def disable_xbox():
    services = ["XblAuthManager", "XblGameSave", "XboxNetApiSvc"]
    for s in services:
        os.system(f"sc stop {s} && sc config {s} start= disabled")


def restore_default_windows_update():
    restore_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "NoAutoUpdate")
    restore_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "DisableWindowsUpdateAccess")
    restore_reg(r"SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate", "ExcludeWUDriversInQualityUpdate")
    restore_reg(r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\WindowsUpdate", "DoNotConnectToWindowsUpdateInternetLocations")
    ctk.CTkLabel(app, text="✅ Windows 更新恢复成功！", text_color="green").pack(pady=10)

def restore_default_installs():
    restore_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "DisallowRun")
    restore_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoRun")
    restore_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoAddDevices")
    restore_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoInstall")
    restore_reg(r"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer", "NoInstallDriveTypeAutoRun")
    restore_reg(r"SOFTWARE\Policies\Microsoft\Windows\Installer", "DisableMSI")
    restore_reg(r"SOFTWARE\Policies\Microsoft\Windows\Installer", "NoShellExecute")
    ctk.CTkLabel(app, text="✅ 安装程序恢复成功！", text_color="green").pack(pady=10)


def apply():
    if options["禁用系统还原"].get(): disable_restore()
    if options["禁用 Windows 更新 & BITS"].get(): disable_updates()
    if options["禁止安装 & 运行程序"].get(): block_installs()
    if options["卸载 OneDrive"].get(): remove_onedrive()
    if options["禁用 Cortana"].get(): disable_cortana()
    if options["关闭视觉特效"].get(): visual_effects()
    if options["关闭广告 & 应用推荐"].get(): ads_disable()
    if options["关闭后台应用"].get(): disable_bg_apps()
    if options["禁用遥测 & 数据收集"].get(): disable_telemetry()
    if options["禁用 Windows 错误报告"].get(): disable_wer()
    if options["清理临时文件"].get(): clean_temp()
    if options["禁用 Xbox 相关服务"].get(): disable_xbox()
    ctk.CTkLabel(app, text="✅ 优化完成，建议重启电脑！", text_color="green").pack(pady=10)


def toggle_all():
    select = all_selected.get()
    for option in options.values():
        option.set(select)


def open_gitee():
    webbrowser.open("https://gitee.com/CTFRoy/optimizer.git")


ctk.CTkLabel(app, text="请选择要应用的优化选项：", font=("微软雅黑", 16)).pack(pady=10)
for name, var in options.items():
    ctk.CTkCheckBox(app, text=name, variable=var).pack(anchor="w", padx=40)


all_selected = ctk.BooleanVar(value=True)
ctk.CTkButton(app, text="全选/取消全选", command=toggle_all).pack(pady=10)


ctk.CTkButton(app, text="✅ 开始优化", command=apply).pack(pady=20)

ctk.CTkLabel(app, text="本工具由ROY开发，旨在帮助提升系统性能！版权 © 2025 ROY. 开源协议：MIT。", font=("微软雅黑", 12), text_color="green").pack(pady=5)
ctk.CTkLabel(app, text="“开源是自由的源泉，推动了创新。” - Richard Stallman", font=("微软雅黑", 10), text_color="gray").pack(pady=5)


ctk.CTkLabel(app, text="Gitee 地址：git clone https://gitee.com/CTFRoy/optimizer.git", font=("微软雅黑", 10), text_color="blue", cursor="hand2",
             command=open_gitee).pack(pady=5)

app.mainloop()
